package sel.me.spring.boot159.web.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import lombok.extern.slf4j.Slf4j;
import sel.me.spring.boot159.web.service.HystrixTestService;

/**
 * 信号量隔离
 * @author shenenlu 2021年05月26日 下午16:18:34
 */
@Slf4j
public class HystrixTestCommandSemaphore extends HystrixCommand<Integer> {

    private HystrixTestService hystrixTestService;

    public HystrixTestCommandSemaphore(HystrixTestService hystrixTestService) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("orderService"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("queryByOrderId"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withCircuitBreakerRequestVolumeThreshold(10) //至少有10个请求，熔断器才进行错误率的计算
                        .withCircuitBreakerSleepWindowInMilliseconds(5000)//熔断器中断请求5秒后会进入半打开状态,放部分流量过去重试
                        .withCircuitBreakerErrorThresholdPercentage(50)//错误率达到50开启熔断保护
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                        .withExecutionIsolationSemaphoreMaxConcurrentRequests(10)));//最大并发请求量
        this.hystrixTestService = hystrixTestService;
    }

    @Override
    protected Integer run() {
        return hystrixTestService.queryByOrderId();
    }

    @Override
    protected Integer getFallback() {
        return -1;
    }




}
